import 'dart:io';

import 'package:gate_cli/exception/errors.dart';
import 'package:gate_cli/utils/print.dart';

/// Author: Shper
/// Created: 2023/9/6
class FileUtil {

  FileUtil._();

  static void replaceAll(String filePath, Pattern from, String replace) {
    try {
      var file = File(filePath);
      var content = file.readAsStringSync();
      var modifyContent = content.replaceAll(from, replace);
      file.writeAsStringSync(modifyContent);
    } catch (e) {
      printRed('$e');
      throw new CommandRunError('读写文件失败，请确认认文件是否正常');
    }
  }

  static void changeContent(String filePath, Pattern pattern, String replaceContent) {
    try {
      var file = File(filePath);
      var lines = file.readAsLinesSync();
      var resultLines = '';
      lines.forEach((content) {
        if (content.startsWith(pattern)) {
          content = replaceContent;
        }
        resultLines += "${content}\n";
      });
      file.writeAsStringSync(resultLines);
    } catch (e) {
      printRed('$e');
      throw new CommandRunError('读写文件失败，请确认认文件是否正常');
    }
  }

}